﻿using SIG.WeiXin;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Xml;

namespace SIG.Web.Controllers
{
    public class WeiXinController : Controller
    {
       
        // GET: /WeiXin/
        [HttpGet]
        public ContentResult Index(string echostr, string signature, string timestamp, string nonce)
        {
            if (WXHelper.CheckSignature(signature, timestamp, nonce))
            {
                return Content(echostr);
            }
            return Content("");
        }

        //public ContentResult Valid(string echostr,string signature, string timestamp, string nonce)
        //{
        //    if (CheckSignature(signature, timestamp, nonce))
        //    {
        //        return Content(echostr);
        //    }
        //    return Content("");
        //}

        [HttpPost]
        public ContentResult Index()
        {
            StreamReader stream = new StreamReader(Request.InputStream);
            string weixinXML = stream.ReadToEnd();

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(weixinXML);

            XmlNodeList list = doc.GetElementsByTagName("xml");
            XmlNode xn = list[0];
            string FromUserName = xn.SelectSingleNode("//FromUserName").InnerText;
            string ToUserName = xn.SelectSingleNode("//ToUserName").InnerText;

            string MsgType = xn.SelectSingleNode("//MsgType").InnerText;

            string content = "", menu = "";
            if (MsgType.Equals("event"))
            {
                content = "欢迎你的加入！";
            }
            else
            {
                content = xn.SelectSingleNode("//Content").InnerText;
            }

            //content就是你要回复的内容，此间的业务逻辑可以自己定义


            string strresponse = "<xml>";
            strresponse = strresponse + "<ToUserName><![CDATA[" + FromUserName + "]]></ToUserName>";
            strresponse = strresponse + "<FromUserName><![CDATA[" + ToUserName + "]]></FromUserName>";
            strresponse = strresponse + "<CreateTime>" + DateTime.Now.Ticks.ToString() + "</CreateTime>";
            strresponse = strresponse + "<MsgType><![CDATA[text]]></MsgType>";
            strresponse = strresponse + "<Content><![CDATA[" + content + menu + "]]></Content>";
            strresponse = strresponse + "<FuncFlag>0<FuncFlag>";
            strresponse = strresponse + "</xml>";

            //   Response.Write(strresponse);


            return Content(strresponse);
        }

       


        /// <summary>  
        /// 处理微信发来的请求   
        /// </summary>  
        /// <param name="xml"></param>  
        public void processRequest(String xml)
        {
            
        }

      
    }
}